package controller;

import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.Provider;
import pojo.User;
import service.provider.ProviderService;
import tools.PageSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class ProviderController {
    @Resource
    private ProviderService providerService;

    @RequestMapping(value="/providerlist")
    public String getProviderList(Model model, HttpSession session,
                              @RequestParam(value="queryname",required=false) String queryProName,
                              @RequestParam(value="queryProAddress",required=false) String queryProAddress,
                              @RequestParam(value="pageIndex",required=false) String pageIndex) throws Exception{
        if(session.getAttribute("user") == null){ //如果用户没有登录就直接来到providerlist就回到syserror
            return "redirect:/syserror";
        }
        List<Provider> providerList = null;
        //设置页面容量
        int pageSize = 5;
        //当前页码
        int currentPageNo = 1;

        if(queryProName == null){
            queryProName = "";
        }
        if(queryProAddress == null){
            queryProAddress="";
        }

        if(pageIndex != null){
            try{
                currentPageNo = Integer.valueOf(pageIndex);
            }catch(NumberFormatException e){
                return "redirect:/syserror";
            }
        }
        //总数量（表）
        int totalCount	= providerService.getProviderCount(queryProName,queryProAddress);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
//        int start = 0;
        //控制首页和尾页

        //设置分页的每一页的显示从哪里开始
        int start = ((currentPageNo-1) * pageSize);

        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }

        //这里的查询limit需要进行改动
        providerList = providerService.getProviderListByPage(queryProName,queryProAddress,start,pageSize);
        model.addAttribute("providerList", providerList);
        model.addAttribute("queryProName", queryProName);
        model.addAttribute("queryProAddress", queryProAddress);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", currentPageNo);
        return "providerlist";
    }

    @RequestMapping("/provideradd")
    public String addProvider(){
        return "provideradd";
    }

    @PostMapping("/provideraddsave")
    public String addProviderAndSave(Provider provider,HttpSession session){
        // 添加供应商表的createdBy值
        provider.setCreatedBy(((User)session.getAttribute("user")).getId());
        //添加供应商表的createdate值
        provider.setCreationDate(new Date());
        if (providerService.addProvider(provider)==true){
            return "redirect:/providerlist";
        }
        return "provideradd";
    }

    @RequestMapping("/providermodify")
    public String getProviderById(@RequestParam Integer pid,Model model){
        Provider provider = providerService.getProviderById(pid);
        model.addAttribute("provider",provider);
        return "providermodify";
    }

    @PostMapping("/providermodifysave")
    public String modifyProviderAndSave(Provider provider,HttpSession session){
        // 修改供应商表的modifyBy值
        provider.setModifyBy(((User)session.getAttribute("user")).getId());
        provider.setModifyDate(new Date());
        if (providerService.modify(provider)){
            return "redirect:/providerlist";
        }
        return "providermodify";
    }

    //查看用户
    @RequestMapping(value="/providerview")
    public String view(@RequestParam Integer pid,Model model){
        Provider provider = providerService.getProviderById(pid);
        model.addAttribute("provider",provider);
        return "providerview";
    }

    //判断是否存在proCode
    @RequestMapping(value="/pcexist")
    @ResponseBody
    public Object pcexist(@RequestParam String proCode){
        String data="{\"proCode\":\"noexist\"}";  //初始化字符串
        if(proCode==null||proCode.length()==0){  //如果proCode是空值
            data="{\"proCode\":\"exist\"}";  //空值直接返回已存在
        }
        else{
            Provider provider = providerService.selectProCodeExist(proCode);
            if(provider!=null)
                data="{\"proCode\":\"exist\"}";
            else
                data="{\"proCode\":\"noexist\"}";
        }
        return JSONArray.toJSONString(data);//将data转为json对象,并将结果发回给当前页面
    }

    //删除供应商数据
    @RequestMapping(value="/delprovider")
    @ResponseBody
    public Object delprovider(@RequestParam int pid){
        String data="{\"delResult\":\"false\"}";  //初始化字符串
        boolean result= providerService.deleteProviderById(pid);
        if(result==true)
            data="{\"delResult\":\"true\"}"; //删除成功
        else
            data="{\"delResult\":\"false\"}"; //删除失败
        return JSONArray.toJSONString(data);//将data转为json对象,并将结果发回给当前页面
    }

}
